<?php
namespace App\Services;
use App\Helpers\Api\PayTrait;
use App\Helpers\Api\TtMiniTrait;
use App\Models\Appoint;
use App\Models\Balance;
use App\Models\HoneyBalance;
use App\Models\Material;
use App\Models\Order;
use App\Models\User;

class AppointService {
    use PayTrait, TtMiniTrait;

    public static function is_buy($user_id, $entity_id) {
        return Order::where('user_id', $user_id)
            ->where('cookbook_id', $entity_id)
            ->where('status', Order::PAID_SUCCESS)->exists();
    }

    public static function create_pay($user_id, $entity_id) {
        $self = new self();
        $user = User::find($user_id);
        $prefix = 'ap';
        $model = new Appoint();

        $out_trade_no = create_order_no($prefix);
        $entity = null;

        $entity = $model->find($entity_id);
        $amount = $entity->paid_amount;
        $subject = $entity->title;
        $pay_type = $entity->buy_type;

        try {
            \DB::beginTransaction();
            $config = [
                'out_trade_no' => $out_trade_no,
                'total_fee' => $amount,
                'body' => $subject,
                'openid' => $user->openid,
                'trade_type' => 'JSAPI'
            ];
            $result = $self->payWx()->miniapp($config);
            \DB::commit();
            return ['pay_type' => $pay_type, 'result' => $result];
        }catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

}
